package com.heima.wemedia.service.impl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.file.service.impl.MinIOFileStorageService;
import com.heima.model.common.constants.WmNewsConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;


    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) throws IOException {
        if (ObjectUtil.isEmpty(file)){
            return ResponseResult.errorResult(501, "图片上传参数失败");
        }
        //1.上传图片到minio中
        InputStream inputStream = file.getInputStream();
        String filename = file.getOriginalFilename();
        String UUId = UUID.randomUUID().toString();
        filename = filename+UUId;
        String urlPath = fileStorageService.uploadImgFile(null, filename, inputStream);
        if (StrUtil.isEmpty(urlPath)){
            return ResponseResult.errorResult(501, "图片上传失败");
        }
        //2.创建实体类保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(urlPath);
        wmMaterial.setType(Short.valueOf("0"));
        wmMaterial.setIsCollection(Short.valueOf("0"));
        Date date = new Date();
        wmMaterial.setCreatedTime(date);
        wmMaterialMapper.insert(wmMaterial);
        return ResponseResult.okResult(urlPath);
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.创建分页
        IPage<WmMaterial>page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> iPage=null;
        //判断查询的是全部还是收藏列表
        if (dto.getIsCollection()==0){
            iPage = wmMaterialMapper
                    .selectPage(page, null);
        }else {
            //调用mp分页查询方法
            iPage = wmMaterialMapper
                    .selectPage(page,
                            new LambdaQueryWrapper<WmMaterial>().eq(WmMaterial::getIsCollection,dto.getIsCollection())
                    );
        }
        List<WmMaterial> wmMaterialList = iPage.getRecords();
        long t = iPage.getTotal();
        int inttotal = (int) t;
        Integer total = new Integer(inttotal);
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),total);
        result.setData(wmMaterialList);
        return result;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(501,"参数失效");
        }
        Integer count = wmNewsMaterialMapper.selectCount(
                new LambdaQueryWrapper<WmNewsMaterial>()
                        .eq(WmNewsMaterial::getMaterialId, id));
        if (count>0){
            return ResponseResult.errorResult(501, "文件删除失败");
        }
        int result = wmMaterialMapper.deleteById(id);
        if (result==0){
            return ResponseResult.errorResult(1002, "数据不存在");
        }
        return ResponseResult.okResult(200,"操作成功");
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        //根据id更新is_collection字段
        boolean result = this.lambdaUpdate().set(WmMaterial::getIsCollection,0)
                .eq(WmMaterial::getId, id).update();
        if (result==false){
            return ResponseResult.errorResult(501,"参数失效");
        }
        return ResponseResult.okResult(200,"操作成功");
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //根据id更新is_collection字段
        boolean result = this.lambdaUpdate().set(WmMaterial::getIsCollection, 1)
                .eq(WmMaterial::getId, id).update();
        if (result==false){
            return ResponseResult.errorResult(501,"参数失效");
        }
        return ResponseResult.okResult(200,"操作成功");
    }
}
